let token = getToken();
let user = JSON.parse(window.localStorage.getItem("userInfo"));
let url;
let currentNodeName = null;
var treeData = []
var res = playGet(`/v1/api/users/queue/${user.id}`);
const maxPnum = res.data.nummber;
if (res.code == 200) {
  const {
    data: { id },
  } = res;
  const promiseList = [];
  for (let i = 1; i < 4; i++) {
    const promiseFunc = new Promise((resolve) => {
      resolve(
        $.ajax({
          url: `${server}/v1/api/setting/tj/queue/zhu/${id}/${i}`,
          // url: `http://47.111.243.54:504/v1/api/setting/tj/queue/zhu/1/${i}`, // 有数据
        })
      );
    });
    promiseList.push(promiseFunc);
  }

  const showCurrentUserAtTreeChart = (pnum) => {
    const otherNode = $(".other");
    for (let i = 0; i < otherNode.length; i++) {
      if (String(pnum) === otherNode.eq(i).text()) {
        otherNode.eq(i).addClass("active");
      }
    }
  };

  const setLastShowNode = (pnum) => {
    typeof pnum === "string" && (pnum = Number(pnum));
    const otherNode = $(".other-next");
    for (let i = 0; i < otherNode.length; i++) {
      const nodeVal = Number(otherNode.eq(i).text());
      if (nodeVal > pnum) {
        // otherNode.eq(i).addClass('not-show')
        otherNode.eq(i).html("");
      }
    }
  };

  const toRenderTeamList = (list) => {
    const allPnum = [];
    const teamListContainer = $("#dataList");
    const allTeamListNode = list
      .map((i) => {
        const { code, data } = i;
        if (data.length > 0) {
          const teamList = data
            .map((j, jIndex) => {
              console.log('dsad', j)
              const { id, pnum, name, mobile, userName } = j;
              allPnum.push(pnum);
              const isCurrentUser =
                id ===
                JSON.parse(localStorage.getItem("userInfo") || { id: null }).id;
              isCurrentUser && showCurrentUserAtTreeChart(pnum);
              const teamListTemplate = `
											<li class="${isCurrentUser ? "is-current-user" : ""}">
												<img src="phoneContent/img/headImg.png"/>
												<div class="fr">
													<p class="t_name">账号:${userName}</p>
                          <p class="t_name">手机号:${mobile}</p>
                          <p class="t_id">所占点位：${pnum}</p>
													<p class="t_id">ID：${id}</p>
												</div>
											
											</li>
											`;
              return teamListTemplate;
            })
            .join("");
          return `<div class="team-list-div">${teamList}</div>`;
        } else {
          return ''
        }

      })
      .join("");
    setLastShowNode(allPnum.length > 0 ? allPnum.reduce((a, b) => (a > b ? a : b)) : 0);
    teamListContainer.append(allTeamListNode);
  };
  // var allCardData = {}
  var showAllTree = []
  var currentNode = []
  var fatherIds = []
  const getTreeData = (data) => {
    getLeverData(data)
    let right = '>'
    const list = showAllTree.map(item => {
      const teamListTemplate = getTemplate(item, right)
        return teamListTemplate
    }).join("")
    $("#treeDataList").html(list)
  }
  const getLeverData = (data, id) => {
    let userId = id || JSON.parse(localStorage.getItem("userInfo")).id
    if (!Array.isArray(data) && data && data.id === userId) {
      showAllTree = [data]
      return data
    }
    if (data === null) return []
    if (Array.isArray(data)) {
      for (let item of data) {
        if (item.id === userId) {
          if (id) {currentNode = data} else {showAllTree = data}
          
          return data
        } else {
          // fatherId = item.id
          getLeverData(item.children, id)
        }
      }
    } else {
      getLeverData(data.children, id)
    }
    
    
  }
  var count = 0
  $('#treeDataList').on('click', function(e){
    if (!$(e.target).hasClass('to-right')) return
    const userId = $(e.target).attr('userId')
    new Promise((resolve) =>
      resolve(
        $.ajax({
          url: `${server}/v1/api/team/tu/${userId}`,
        })
      )
    ).then(res => {
      const queueId = res.data
      // const queueId = '827246627436625929'
      new Promise((resolve) =>
        resolve(
          $.ajax({
            url: `${server}/v1/api/setting/tj/user/queue/${userId}/${queueId}`,
          })
        )
      ).then(res => {
        count++
          let right = '>'
          let left = '<'
          // if (userId === JSON.parse(localStorage.getItem("userInfo")).id) {
          //   allCardData = res.data
          // }
          if (res.data.children === null) return
          const list = res.data.children.map(item => {
            const teamListTemplate = getTemplate(item, right)
              return teamListTemplate
          }).join("")
          $('#treeDataList').addClass('has-left')
          fatherIds.push(userId)
          const toLeft = `<li class="to-left" id="toLeft" fatherId="${userId}">${left}</li>`
        $("#treeDataList").html(toLeft+list)
      })
    })
    
  })
  $('#treeDataList').on('click', function(e){
    if (!$(e.target).hasClass('to-left')) return
  // $('#toLeft').on('click', function(e) {
    let data = showAllTree
    getLeverData(data, $(e.target).attr('fatherId'))
    data = currentNode
    const list = data.map(item => {
      const teamListTemplate = getTemplate(item, '>')
        return teamListTemplate
    }).join("")
    $('#treeDataList').addClass('has-left')
    const left = '<'
    fatherIds.pop()
    const toLeft = count > 1 ?`<li class="to-left" id="toLeft" fatherId="${fatherIds.pop()}">${left}</li>`: ''
    console.log('count', count)
    $("#treeDataList").html(toLeft+list)
    count--
  })
  const getTemplate = (item, right) => {
    return `
              <li class="${"", 'card-right'}" userId="${item.id}" queueId="${item.queueId}">
                <img src="phoneContent/img/headImg.png"/>
                <div class="fr">
                  <p class="t_name">账号:${item.name}</p>
                  <p class="t_name">手机号:${item.mobile}</p>
                </div>
                <div class="to-right" userId="${item.id}" style="${item.children && item.children.length ? '': 'display:none'}">${right}</div>
              </li>
              `;
  }

  const toRenderTreeNode = (resData) => {
    const treeContainer = $("#tree_chart_container");
    let { code, data } = resData;
    // if (!data) data = mockData
    if (!data) {
      treeContainer.show();
      treeContainer.children().not(".other-next-container").hide();
      treeContainer
        .children(".other-next-container")
        .eq(0)
        .addClass("not-top-line");
      return;
    }
    if (code === 200 && data) {
      treeContainer.show();
      // 树
      getTreeData(data)
    }
  };

  function getNodeData() {
    new Promise((resolve) =>
      resolve(
        $.ajax({
          url: `${server}/v1/api/team/node/brother/${user.id}`,
        })
      )
    )
      .then(toRenderTreeNode)
      .then(() => {
        Promise.allSettled(promiseList)
          .then((res) => {
            const teamListData = [];
            res.forEach((i) => {
              const { status, value } = i;
              if (status !== "fulfilled") return console.log("数据获取失败");
              teamListData.push(value);
            });
            return teamListData;
          })
          // .then(toRenderTreeNextNodeList)
          .then(toRenderTeamList)
          .catch((err) => console.log(err));
      });
  }

  getNodeData();
} else {
  mui.alert(res.msg);
}


